<template>
  <div id="QuestionResource">
    <a-form layout="inline" style="margin-bottom: 8px">
      <a-form-model-item label="课程信息" prop="curriculumId">
        <a-select v-model="curriculumId" style="width: 180px">
          <a-select-option
            v-for="item in curriculumIdList"
            :key="item.id"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-model-item>
      <a-form-item label="关键字" class="searchItem">
        <a-input v-model="keyword" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="getData"> 查询 </a-button>
      </a-form-item>
    </a-form>
    <div style="display: flex; justify-content: flex-end">
      <a-button
        v-if="!curriculumId"
        type="primary"
        icon="cloud-upload"
        @click="messageShow"
        >上传</a-button
      >
      <a-upload
        v-else
        ref="uploadRef"
        class="upload"
        name="file"
        :multiple="true"
        :show-upload-list="false"
        :custom-request="customUploadRequest"
        accept=".xls,.xlsx"
      >
        <a-button icon="cloud-upload">上传</a-button>
      </a-upload>
      <a-button type="primary" style="margin-left: 10px" @click="addbtn"
        >新增</a-button
      >
      <a-button type="primary" style="margin-left: 10px" @click="downClick"
        >导出</a-button
      >
      <!-- <a-button type="primary" style="margin-left: 10px">删除</a-button> -->
    </div>
    <a-table
      :columns="columns"
      :scroll="{ y: 500 }"
      style="margin-top: 30px"
      :data-source="tableData"
      :pagination="tablePagination"
      :rowKey="(record, index) => index"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      @change="handleTableChange"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button
          v-if="record.operation"
          type="primary"
          @click="PermissionClick(record)"
          style="margin-right: 10px"
          >分配权限</a-button
        >
        <a-button
          v-if="record.operation"
          type="primary"
          @click="editClick(record)"
          style="margin-right: 10px"
          >修改</a-button
        >
        <a-button
          v-if="record.operation"
          type="danger"
          @click="deleteClick(record)"
          >删除</a-button
        >
      </template>
    </a-table>
    <a-modal
      v-model="visible"
      :maskClosable="false"
      :title="title"
      @cancel="handleCancel"
    >
      <a-form-model
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item label="课程名称" prop="curriculumId">
          <a-select v-model="form.curriculumId" style="width: 236px">
            <a-select-option
              v-for="item in curriculumIdList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="分数" prop="points">
          <a-input v-model="form.points" />
        </a-form-model-item>
        <a-form-model-item label="试题内容" prop="topic">
          <a-input v-model="form.topic" />
        </a-form-model-item>
        <a-form-model-item label="试题类型" prop="type">
          <a-select v-model="form.type" @change="typeChange">
            <a-select-option
              v-for="item in typeList"
              :key="item.id"
              :value="item.id"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item v-if="!isJudgment" label="选项A" prop="optionA">
          <a-input v-model="form.optionA" />
        </a-form-model-item>
        <a-form-model-item v-if="!isJudgment" label="选项B" prop="optionB">
          <a-input v-model="form.optionB" />
        </a-form-model-item>
        <a-form-model-item v-if="!isJudgment" label="选项C" prop="optionC">
          <a-input v-model="form.optionC" />
        </a-form-model-item>
        <a-form-model-item v-if="!isJudgment" label="选项D" prop="optionD">
          <a-input v-model="form.optionD" />
        </a-form-model-item>
        <a-form-model-item label="答案" prop="solution">
          <a-input v-if="!isJudgment" v-model="form.solution" />
          <a-select v-else v-model="form.solution">
            <a-select-option
              v-for="item in JudgmentList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" class="modalCancel" @click="handleCancel"
          >取消</a-button
        >
        <a-button key="submit" @click="primaryClick" type="primary">
          确定
        </a-button>
      </template>
    </a-modal>
    <a-modal v-model="visible2" :maskClosable="false" title="分配权限">
      <a-form-model
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        ref="formRef2"
        :model="form2"
        :rules="rules2"
      >
        <a-form-model-item label="教员选择" prop="userIds">
          <a-select
            v-model="form2.userIds"
            style="width: 236px"
            mode="multiple"
            :maxTagCount="1"
          >
            <a-select-option
              v-for="item in userIdList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" class="modalCancel" @click="handleCancel2"
          >取消</a-button
        >
        <a-button key="submit" @click="primaryClick2" type="primary">
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      FileId: null,
      userIdList: [],
      form2: {
        userIds: [],
      },
      rules2: {
        userIds: [{ required: true, message: "请选择教员", trigger: "blur" }],
      },
      isJudgment: false, //是否展示判断题的答案下拉
      JudgmentList: [
        {
          value: "A",
          label: "正确",
        },
        {
          value: "B",
          label: "错误",
        },
      ],
      topicType: null, //单个题目的题目类型
      curriculumId: "",
      curriculumIdList: [],
      typeList: [
        {
          id: 1,
          label: "单选",
        },
        {
          id: 2,
          label: "多选",
        },
        {
          id: 3,
          label: "判断",
        },
      ],
      courseNameList: [],
      courseList: [], //课程下拉列表
      course: null, //课程所选中的值
      keyword: null, //关键字
      form: {
        id: null, //训练计划id
        curriculumId: "", // 课程名称
        topic: "", //试题内容
        type: "", //试题类型
        optionA: "", //选项A
        optionB: "", //选项B
        optionC: "", //选项C
        optionD: "", //选项D
        solution: "", //答案
      },
      rules: {
        curriculumId: [
          { required: true, message: "请选择课程名称", trigger: "blur" },
        ],
        topic: [{ required: true, message: "请输入试题内容", trigger: "blur" }],
        points: [{ required: true, message: "请输入分数", trigger: "blur" }],
        type: [{ required: true, message: "请选择试题类型", trigger: "blur" }],
        // optionA: [{ required: true, message: "请输入选项A", trigger: "blur" }],
        // optionB: [{ required: true, message: "请输入选项B", trigger: "blur" }],
        // optionC: [{ required: true, message: "请输入选项C", trigger: "blur" }],
        // optionD: [{ required: true, message: "请输入选项D", trigger: "blur" }],
        solution: [{ required: true, message: "请输入答案", trigger: "blur" }],
      },
      visible: false,
      visible2: false,
      title: null,
      selectedRowKeys: [],
      columns: [
        //主页table列的配置
        {
          title: "课程名称",
          dataIndex: "curriculumName",
          customRender: (text, record) => {
            return record.curriculumName ? record.curriculumName : "—";
          },
        },
        {
          title: "试题内容",
          dataIndex: "topic",
          customRender: (text, record) => {
            return record.topic ? record.topic : "—";
          },
        },
        {
          title: "试题类型",
          dataIndex: "type",
          //1是单选,2是多选,3是选择题
          customRender: (text, record) => {
            if (record.type == 1) {
              return "单选";
            } else if (record.type == 2) {
              return "多选";
            } else if (record.type == 3) {
              return "判断题";
            }
          },
        },
        {
          title: "选项A",
          dataIndex: "optionA",
          customRender: (text, record) => {
            return record.optionA ? record.optionA : "—";
          },
        },
        {
          title: "选项B",
          dataIndex: "optionB",
          customRender: (text, record) => {
            return record.optionB ? record.optionB : "—";
          },
        },
        {
          title: "选项C",
          dataIndex: "optionC",
          customRender: (text, record) => {
            return record.optionC ? record.optionC : "—";
          },
        },
        {
          title: "选项D",
          dataIndex: "optionD",
          customRender: (text, record) => {
            return record.optionD ? record.optionD : "—";
          },
        },
        {
          title: "答案",
          dataIndex: "solution",
          customRender: (text, record) => {
            return record.solution ? record.solution : "—";
          },
        },
        {
          title: "操作",
          width: 280,
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [
        //主页表格的数据
      ],
      tablePagination: {
        //主页表格的分页器
        total: 0,
        current: 1,
        pageSize: 10,
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true, //是否可以改变 pageSize
      },
    };
  },
  created() {
    this.getData(); //获取列表数据
    this.getCurriculumIdList(); //获取课程的下拉
    this.getUserIdList(); //获取教员的下拉选项
  },
  methods: {
    handleCancel2() {
      this.form2.userIds = [];
      this.$refs.formRef2.resetFields();
      this.visible2 = false;
    },
    primaryClick2() {
      let data = {
        id: this.FileId,
        userIds: this.form2.userIds,
      };
      this.$axios.post("/question/allot", data).then((res) => {
        if (res.code == 200) {
          this.$message.success("分配权限成功");
          this.handleCancel2();
          this.getData();
        }
      });
    },
    getUserIdList() {
      this.$axios.get("/educator/options").then((res) => {
        if (res.code == 200) {
          this.userIdList = res.data;
        }
      });
    },
    PermissionClick(row) {
      this.FileId = row.id;
      this.visible2 = true;
    },
    downClick() {
      if (!this.curriculumId) {
        this.$message.warning("请选择课程信息");
        return;
      }
      let obj = this.curriculumIdList.find(
        (item) => item.id === this.curriculumId
      );
      let params = {
        keyword: this.keyword,
        curriculumId: this.curriculumId,
      };
      this.$axios
        .get("/question/export", {
          params,
          responseType: "blob", // 关键：指定返回数据类型为 blob
        })
        .then((res) => {
          const downloadUrl = window.URL.createObjectURL(res);
          const link = document.createElement("a"); // 创建隐藏的下载链接
          link.href = downloadUrl;
          const filename = obj.name; //文件名可以从响应头或请求参数中获取
          link.download = filename;
          link.click();
          link.remove();
        });
    },
    customUploadRequest({ file, onSuccess, onError }) {
      const formData = new FormData();
      // 添加文件到 FormData
      formData.append("file", file);
      // 如果需要其他参数，可以在这里添加
      // formData.append('additionalParam', 'value');
      let params = {
        curriculumId: this.curriculumId,
      };
      this.$axios.post("/question/import", formData, { params }).then((res) => {
        if (res.code == 200) {
          this.$message.success("上传成功");
          this.curriculumId = null;
          this.getData();
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    messageShow() {
      if (!this.curriculumId) {
        this.$message.warning("请选择课程信息");
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.tablePagination.current = pagination.current;
      this.tablePagination.pageSize = pagination.pageSize;
      this.getData();
    },
    getCurriculumIdList() {
      //课程下拉框
      this.$axios.get("/curriculum/options").then((res) => {
        this.curriculumIdList = res.data;
      });
    },
    addbtn() {
      this.title = "新增";
      this.visible = true;
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    typeChange(val) {
      this.topicType = val;
      if (val == 3) {
        //为判断题类型时
        this.isJudgment = true;
      } else {
        this.isJudgment = false;
      }
    },
    editClick(row) {
      //编辑
      this.$axios
        .get("/question/detail", {
          params: {
            id: row.id,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.form = res.data;
            this.form.id = row.id;
            this.topicType = res.data.type;
            this.title = "编辑";
            this.visible = true;
          }
        });
    },
    handleCancel() {
      this.topicType = null;
      this.form = {
        id: null,
        curriculumId: "", // 课程名称
        points: "", //分数
        topic: "", //试题内容
        type: "", //试题类型
        optionA: "", //选项A
        optionB: "", //选项B
        optionC: "", //选项C
        optionD: "", //选项D
        solution: "", //答案
      };
      this.$refs.formRef.resetFields(); //重置表单校验
      this.visible = false;
    },
    primaryClick() {
      this.$nextTick(() => {
        let data = null;
        if (this.topicType == 1) {
          data = {
            id: this.form.id,
            curriculumId: this.form.curriculumId, // 课程名称
            points: this.form.points, //分数
            topic: this.form.topic, //试题内容
            type: this.form.type, //试题类型
            optionA: this.form.optionA, //选项A
            optionB: this.form.optionB, //选项B
            optionC: this.form.optionC, //选项C
            optionD: this.form.optionD, //选项D
            solution: this.form.solution, //答案
          };
        } else if (this.topicType == 2) {
          data = {
            id: this.form.id,
            curriculumId: this.form.curriculumId, // 课程名称
            points: this.form.points, //分数
            topic: this.form.topic, //试题内容
            type: this.form.type, //试题类型
            optionA: this.form.optionA, //选项A
            optionB: this.form.optionB, //选项B
            optionC: this.form.optionC, //选项C
            optionD: this.form.optionD, //选项D
            solution: this.form.solution, //答案
          };
        } else if (this.topicType == 3) {
          data = {
            id: this.form.id,
            curriculumId: this.form.curriculumId, // 课程名称
            points: this.form.points, //分数
            topic: this.form.topic, //试题内容
            type: this.form.type, //试题类型
            solution: this.form.solution, //答案
          };
        }
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            if (this.title == "新增") {
              this.$axios.post("/question/create", data).then((res) => {
                if (res.code == 200) {
                  this.$message.success("新增成功");
                  this.getData();
                  this.handleCancel();
                }
              });
            } else if (this.title == "编辑") {
              this.$axios.put("/question/update", data).then((res) => {
                if (res.code == 200) {
                  this.$message.success("编辑成功");
                  this.getData();
                  this.handleCancel();
                }
              });
            }
          } else {
            console.log("校验失败");
          }
        });
      });
    },
    async getData() {
      let { data } = await this.$axios.get("/question/page/list", {
        params: {
          page: this.tablePagination.current,
          size: this.tablePagination.pageSize,
          keyword: this.keyword, //关键字(也是题目内容)
          curriculumId: this.curriculumId, //课程id
        },
      });
      this.tableData = data.records;
      this.tablePagination.total = data.total;
    },
    deleteClick(row) {
      //点击删除
      let data = {
        id: row.id,
      };
      let that = this;
      this.$confirm({
        title: "确认删除?",
        content: "您确定要删除此项吗?",
        onOk() {
          that.$axios.delete("/question/delete", { data }).then((res) => {
            if (res.code == 200) {
              that.$message.success("删除成功");
              that.getData();
            }
          });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
  },
};
</script>

<style lang="scss">
#QuestionResource {
  // .upload {
  //   position: relative;
  //   .ant-upload-list {
  //     position: absolute;
  //     right: 0;
  //     .ant-upload-list-item {
  //       width: 200px;
  //     }
  //   }
  // }
}
</style>